﻿// Copyright (c) Microsoft Corporation
// The Microsoft Corporation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

#nullable enable

using System;
using System.Threading.Tasks;
using Microsoft.CommandPalette.Extensions;
using Microsoft.CommandPalette.Extensions.Toolkit;
using Windows.Storage;

namespace SamplePagesExtension.Pages;

internal sealed partial class SampleMarkdownImagesPage : ContentPage
{
    private static readonly Task InitializationTask;

    private static string? _sampleMarkdownText;

    static SampleMarkdownImagesPage()
    {
        InitializationTask = Task.Run(static async () =>
        {
            try
            {
                // prepare data files
                // 1) prepare something in our AppData Temp Folder
                var spaceFile = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/Images/Space.png"));
                var tempFile = await spaceFile!.CopyAsync(ApplicationData.Current!.TemporaryFolder!, "Space.png", NameCollisionOption.ReplaceExisting);

                // 2) and also get an SVG directly from the package
                var svgChipmunkFile = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/Images/FluentEmojiChipmunk.svg"));

                _sampleMarkdownText = GetContentMarkup(
                    new Uri(tempFile.Path!, UriKind.Absolute),
                    new Uri(svgChipmunkFile.Path!, UriKind.Absolute));
            }
            catch (Exception ex)
            {
                ExtensionHost.LogMessage(ex.ToString());
            }
        });
        return;

        static string GetContentMarkup(Uri path1, Uri path2)
        {
            return
          $$"""
            # Images in Markdown Content
            
            ## Available sources:

            - `![Alt Text](https://url)`

            - `![Alt Text](file://url)`
              - ℹ️ Only absolute paths are supported.
            
            - `![Alt Text](data:<mime>;[base64,]<data>)`
              - ⚠️ Only for small amount of data. Parsing large data blocks the UI.

            - `![Alt Text](ms-appx:///url)`
              - ⚠️ This loads from CmdPal's AppData folder, not Extension's, so it's not useful for extensions.

            - `![Alt Text](ms-appdata:///url)`
              - ⚠️ This loads from CmdPal's AppData folder, not Extension's, so it's not useful for extensions.

            ## Examples:

            ### Web URL
            ```xml
            ![painting](https://i.imgur.com/93XJSNh.png)
            ```
            ![painting](https://i.imgur.com/93XJSNh.png)
            
            ```xml
            ![painting](https://i.imgur.com/93XJSNh.png?--x-cmdpal-fit=fit)
            ```
            ![painting](https://i.imgur.com/93XJSNh.png?--x-cmdpal-fit=fit)

            ### File URL (PNG):
            ```xml
            ![green rectangle]({{path1}})
            ```

            ![green rectangle]({{path1}})
            
            ### File URL (SVG):
            ```xml
            ![chipmunk]({{path2}})
            ```
            
            ![chipmunk]({{path2}})
            
            ```xml
            ![chipmunk]({{path2}}?--x-cmdpal-maxwidth=400&--x-cmdpal-maxheight=400&--x-cmdpal-fit=fit)
            ```
            
            ![chipmunk]({{path2}}?--x-cmdpal-maxwidth=400&--x-cmdpal-maxheight=400&--x-cmdpal-fit=fit)
            
            ```xml
            ![chipmunk]({{path2}}?--x-cmdpal-width=64)
            ```
            ![chipmunk]({{path2}}?--x-cmdpal-width=64)

            ## Data URL (PNG):
            ⚠️ Passing large data into Markdown Content is unadvisable, parsing large data URLs can be slow and cause hangs.
            ```xml
            ![QR](...RU5ErkJggg==)
            ```

            ![QR]()

            ### Data URL (SVG):
            ⚠️ Passing large data into Markdown Content is unadvisable, parsing large data URLs can be slow and cause hangs.
            ```xml
            ![emoji](...NiAweiIvPjwvZz48L3N2Zz4=)
            ```
            
            ![emoji]()
            
            ### Data URL (SVG 2):
            ⚠️ Passing large data into Markdown Content is unadvisable, parsing large data URLs can be slow and cause hangs.
            ```xml
            <img alt="emoji 2"
            width="48"
            height="48"
            src="....iIvPjwvZz48L3N2Zz4=" />
            ```
            
            <img alt="emoji 2"
                 width="48"
                 height="48"
                 src="" />
            
            ### MS-APPX URL:
            ⚠️ This loads from CmdPal's AppData folder, not Extension's, so it's not useful for extensions.
            ```xml
            ![Swirl](ms-appx:///Assets/Square44x44Logo.png)
            ```
            
            ![Swirl](ms-appx:///Assets/Square44x44Logo.png)
            
            ### MS-APPDATA URL:
            ⚠️ This loads from CmdPal's AppData folder, not Extension's, so it's not useful for extensions.
            ```xml
            ![Space](ms-appdata:///temp/Space.png)
            ```
            
            ---
            
            # Scaling
            
            For URIs that support query parameters (file, http, ms-appx, ms-appdata), you can provide hints to control scaling
            
            - `--x-cmdpal-fit`
              - `none`: no automatic scaling, provides image as is (default)
              - `fit`: scale to fit the available space
            - `--x-cmdpal-upscale`
              - `true`: allow upscaling
              - `false`: downscale only (default)
            - `--x-cmdpal-width`: desired width in pixels
            - `--x-cmdpal-height`: desired height in pixels
            - `--x-cmdpal-maxwidth`: max width in pixels
            - `--x-cmdpal-maxheight`: max height in pixels 
            
            Currently no support for data: scheme as it doesn't support query parameters at all.
            
            ## Examples
            
            ### No scaling
            ```xml
            ![green rectangle]({{path1}})
            ```
            
            ![green rectangle]({{path1}})
            
            ### Scale to fit (scaling down only by default)
            ```xml
            ![green rectangle]({{path1}}?--x-cmdpal-fit=fit)
            ```

            ![green rectangle]({{path1}}?--x-cmdpal-fit=fit)
            
            ### Scale to fit (in both direction)
            ```xml
            ![green rectangle]({{path1}}?--x-cmdpal-fit=fit&--x-cmdpal-upscale=true)
            ```
            
            ![green rectangle]({{path1}}?--x-cmdpal-fit=fit&--x-cmdpal-upscale=true)
            
            ### Scale to exact width
            ```xml
            ![green rectangle]({{path1}}?--x-cmdpal-width=320)
            ```
            
            ![green rectangle]({{path1}}?--x-cmdpal-width=320)
            """;
        }
    }

    private string _currentContent;

    public SampleMarkdownImagesPage()
    {
        Name = "Sample Markdown with Images Page";
        _currentContent = "Initializing...";
        IsLoading = true;

        _ = InitializationTask!.ContinueWith(_ =>
        {
            _currentContent = _sampleMarkdownText!;
            RaiseItemsChanged();
            IsLoading = false;
        });
    }

    public override IContent[] GetContent() => [new MarkdownContent(_currentContent ?? string.Empty)];
}
